<template>
  <base-breadcrumb class="UpdateArchiveApply-container" :title="breadcrumbTitle">
    <a-spin :spinning="loadingState.isInit || loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="延期归档申请" />
        <custom-form ref="ruleForm" :isValidate="true" :editModel="isDisabled ? 'V' : ''" :rules="rules"
          :form="formInfo" :formList="formItemList">
          <template v-slot:fileList>
            <template v-if="!isDisabled">
              <l-table :fileAutoLoading="false" businessCode="ARC01" :uploadArrys.sync="formInfo.fileList"></l-table>
              <div class="file_prompt">请上传相关佐证资料</div>
            </template>
            <file-link v-else :fileList="formInfo.fileList"></file-link>
          </template>
        </custom-form>
      </a-card>
    </a-spin>
    <div class="tool-btns page-btn-right-top">
      <a-button v-if="!isDisabled" type="primary" :loading="loadingState.isDraft"
        @click="handleSubmit('isDraft')">保存草稿</a-button>
      <a-button v-if="!isDisabled" class="ml12" type="primary" :loading="loadingState.isSubmit"
        @click="handleSubmit('isSubmit')">提交</a-button>
      <a-button class="ml12" type="default" @click="handleClose">关闭</a-button>
    </div>
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { addDelayApply, editDelayApply, getDelayApplyDetail, getPlanTime } from '@/api/office/archiveManage/archiveApply.js'
import { getAuditProject } from '@/api/themeChoose/themeChoose.js'
import moment from 'moment'
import Vue from 'vue'
import { async } from 'regenerator-runtime'

export default {
  name: 'a' + Date.now(),
  data() {
    return {
      loadingState: {
        isInit: false,
        isDetail: false,
        isDraft: false,
        isSubmit: false,
      },
      projectInfo: {},
      formInfo: {
        completionTime: '', // 计划竣工时间
        archiveTime: '', // 原计划归档时间
        fileList: [],
      },
      rules: {
        extendedReason: [{ required: true, message: '请填写申请延期原因', trigger: 'change' }],
        extendedArchiveTime: [{ required: true, message: '请选择', trigger: 'change' }],
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '延期归档申请新增',
        edit: '延期归档申请编辑',
        look: '延期归档申请详情',
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth: true,
          checkStrictly: true,
          disabled: true,
          viewName: "viewName",
        },
        // {
        // {
        //   label: '分公司',
        //   keyName: 'branchOrgName',
        //   viewName: 'branchOrgName',
        //   type: 'BaseInput',
        //   disabled: true,
        // },
        // {
        //   label: '项目名称',
        //   keyName: 'projectName',
        //   viewName: 'projectName',
        //   type: 'BaseInput',
        //   disabled: true,
        // },
        {
          label: '计划竣工时间',
          keyName: 'completionTime',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '原计划归档时间',
          keyName: 'archiveTime',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '申请延期原因',
          keyName: 'extendedReason',
          type: 'BaseTextarea',
          disabled: this.isDisabled,
          span: 24,
          attrs: {
            maxLength: 500
          }
        },
        {
          label: '延期后归档时间',
          keyName: 'extendedArchiveTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (currentDate) => {
              if (this.formInfo.archiveTime) {
                return currentDate.isSameOrBefore(this.formInfo.archiveTime)
              }
              return false
            }
          },
        },
        {
          slot: true,
          keyName: 'fileList',
          label: '上传附件',
          span: 24,
        },
      ]
    },
  },
  async created() {
    this.getAuditProjectReq()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('archive_extended_apply')
  },
  methods: {
    /**
     * 获取延期申请详情信息
     */
    async getDelayApplyDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id,
        }
        if (this.loadingState.isDetail) return
        this.loadingState.isDetail = true
        const res = await getDelayApplyDetail(params)
        this.loadingState.isDetail = false
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
          fileList: res.data.fileInfoList || []
        }
      } catch (e) {
        console.error(e)
        this.loadingState.isDetail = false
      }
    },
    /**
     * 获取计划归档时间
     */
    async getPlanTimeReq(id) {
      try {
        const params = {
          projectId: id
        }
        const res = await getPlanTime(params)
        if (typeof res.data === "string" && res.data) {
          this.formInfo.archiveTime = res.data
        }
      } catch (e) {
        console.error(e)
      }
    },
    /**
     * 获取审核通过的项目列表，筛选出当前账号所选岗位的项目，赋值相关项目信息
     */
    async getAuditProjectReq() {
      try {
        this.loadingState.isInit = true
        const res = await getAuditProject({ auditStatus: 2, projectStatus: "1,2,3,4,5,6" })
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        const target = res.data.find((item) => item.projectDeptId === userInfo?.currentPost?.id)
        if (target) {
          this.formInfo = {
            ...this.formInfo,
            completionTime: target.contractFinishDate, // 竣工时间
            archiveTime: moment(target.contractFinishDate).add(3, 'months').format('YYYY-MM-DD'), // 竣工时间 加3个月， 为原计划归档时间
            branchOrgId: userInfo?.currentPost?.orgId,
            branchOrgName: userInfo?.currentPost?.orgName,
            projectId: target.projectId,
            projectName: target.projectName,
            projectOrgId: userInfo?.currentPost?.id, // 项目部ID
            projectOrgName: userInfo?.currentPost?.name,
          }
        }
        await this.getDelayApplyDetailReq()
        // 如果已经申请通过之后，需要获取延期之后的时间
        await this.getPlanTimeReq(this.formInfo.projectId)
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isInit = false
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'isDraft': 保存草稿  'isSubmit'：提交
     */
    handleSubmit(actionName) {
      this.setProcessConfig = null;
      if (actionName === 'isSubmit') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          if (!this.formInfo.fileList || !this.formInfo.fileList.length) {
            this.$message.warning('请上传相关佐证资料')
            return
          }
          this.invokeSave(actionName)
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      if (this.loadingState[actionName]) return
      try {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        if (userInfo?.currentPost?.code !== 'PD') {
          this.$message.warning('非项目部人员不可填写延期申请')
          return
        }
        this.loadingState[actionName] = true
        const params = {
          ...this.formInfo,
          fileList: void 0,
          auditStatus: actionName === 'isSubmit' ? 1 : 0, // 0：草稿，未提交/1：已提交，待审核，审核中/2:通过/3:驳回
          id: this.$route.query.id,
          fileIds: this.formInfo.fileList.map((item) => item.commonId),
        }
        // 这里只用调修改接口
        const fn = this.pageType === 'add' ? addDelayApply : editDelayApply
        this.submitApprovalConfirm(actionName == 'isSubmit' ? this.processConfig : 6, async (flag) => {
          if (!flag) {
            this.loadingState[actionName] = false
            return
          }
          let res = await fn(params)
          this.loadingState[actionName] = false
          this.$message.success(actionName === 'isDraft' ? '保存成功' : '提交成功')
          if (actionName == 'isSubmit') {
            //提交时，返回id
            this.businessId = this.pageType === 'add' ? res.data : this.$route.query.id;
            this.setProcessConfig = this.processConfig;
            return
          } else {
            this.$multiTab.close()
          }
        })
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    },
    handleClose() {
      this.$close()
    },
  },
}
</script>

<style>

</style>
